from strategy.core.Stg import Stg
import talib as ta


class SingleMaStg(Stg):

    def getParams(self):
        params = [
            {'period': 10},
            {'period': 15},
            {'period': 20},
            {'period': 30},
            {'period': 40},
            {'period': 50},
            {'period': 60}
        ]
        return params

    param = {
        # 'fastPeriod': 10,
        # 'slowPeriod': 30,
        'period': 30,
    }

    def initial(self):
        self.sma = ta.SMA(self.data['close'], self.param['period'])
        return

    def signal(self, index):
        """
        买入: 长均线向上掉头(大趋势向上)或到达支撑位(低点)
        卖出: 长均线向下掉头(大趋势向下)或到达阻力位(顶点)
*
        支撑位:长周期均线上涨,股价或短周期均线与长周期相交的点
        阻力位:长周期均线下降,股价或短周期均线与长周期相交的点
        """
        # 自动跳过无法计算的节点
        if index < self.param['period'] + 1:
            return
        curPrice = self.data.close[index]
        maxVal = curPrice + curPrice * 0.05
        minVal = curPrice - curPrice * 0.05
        for i in range(1, 5):
            if minVal < self.data.close[index - i] < maxVal:
                return  # 过滤震荡行情

        pre = index - 1
        curUp = self.sma[pre] <= self.sma[index]  # 当前节点是否为上升
        preUp = self.sma[pre - 1] <= self.sma[pre]  # 前一个节点是否为上升
        curPrice = self.data.close[index]
        # if (preUp == False and curUp == True) or \
        # 		(preUp and curUp and curPrice <= self.sma[index]):  # 向上掉头 或 到达支撑位
        # 	return 1
        # if (preUp == True and curUp == False) or \
        # 		(not preUp and not curUp and curPrice >= self.sma[index]):  # 向上掉头 或 到达支撑位
        # 	return -1
        if (preUp == False and curUp == True):
            return 1
        if (preUp == True and curUp == False):
            return -1
        return
